package cn.wolfcode.web.modules.linkman.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.customer.entity.TbCustomer;
import cn.wolfcode.web.modules.customer.service.ITbCustomerService;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkmanVo;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;


import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author sjh
 * @since 2024-04-17
 */
@Controller
@RequestMapping("linkman")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;
    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbCustLinkman";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {

        List<TbCustomer> lists = customerService.list();

        mv.addObject("custs", lists);

        mv.setViewName("user/linkman/list");

        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        //查询客户信息
        List<TbCustomer> customer = customerService.list();
        //把数据返回给前端页面
        mv.addObject("custs",customer);

        mv.setViewName("user/linkman/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {

        //查询客户数据返回给前端
        List<TbCustomer> customer = customerService.list();
        mv.addObject("custs",customer);

        mv.setViewName("user/linkman/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);

        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('user:linkman:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String custId) {

        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());
//
////        Page<TbCustLinkmanVo> page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());
////
////        Page<TbCustLinkmanVo> tbCustLinkmanVoPage =entityService.getByPageByparmBycustId(page,parameterName,custId)
//
//
        LambdaQueryChainWrapper<TbCustLinkman> tbCustLinkmanLambdaQueryChainWrapper = entityService.lambdaQuery();
        tbCustLinkmanLambdaQueryChainWrapper
// 所属企业查询
                .eq(!StringUtils.isEmpty(custId),TbCustLinkman::getCustId,custId)
// 模糊查询 -- 根据联系人姓名和电话号码查询
                .and(!StringUtils.isEmpty(parameterName), q->q.like(TbCustLinkman::getLinkman,parameterName)
                        .or()
                        .like(TbCustLinkman::getPhone,parameterName));

        page = tbCustLinkmanLambdaQueryChainWrapper.page(page);




        List<TbCustLinkman> lists = (List<TbCustLinkman>) page.getRecords();
        for (TbCustLinkman tbCustLinkman : lists) {
            String man ="男";
            String woman = "女";
            if(tbCustLinkman.getSex()!=null){
                Integer sex = tbCustLinkman.getSex();
                if (sex==1){
                    tbCustLinkman.setSexToString(man);
                }else if(sex ==0){
                    tbCustLinkman.setSexToString(woman);
                }
            }
        }

//        Page<TbCustLinkmanVo> page = new Page<>(layuiPage.getPage(),layuiPage.getLimit());
//
//        Page<TbCustLinkmanVo> tbCustLinkmanVoPage = entityService.selectByPageByparmByCustId(page, parameterName, custId);
//
//        System.out.println(tbCustLinkmanVoPage);
//
//        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(tbCustLinkmanVoPage));

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustLinkman entity, HttpServletRequest request) {
        entity.setInputTime(LocalDateTime.now());

        SysUser user=(SysUser) request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUser(user.getUserId());
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('user:linkman:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

}
